package com.yuebook.smartrpc.framework.serialization;

import com.yuebook.smartrpc.framework.serialization.common.SerializerType;
import com.yuebook.smartrpc.framework.serialization.engine.SerializerEngine;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import java.util.List;

/**
 * @author honglei
 * @date 2018/11/19 下午9:17
 */
public class NettyDecodeHandler extends ByteToMessageDecoder {

    private Class<?> clazz;

    private SerializerType serializerType;

    public NettyDecodeHandler(Class clazz, SerializerType serializerType) {
        this.clazz = clazz;
        this.serializerType = serializerType;
    }

    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf in, List<Object> out)
        throws Exception {
        //字节数目int的4个字节
        if (in.readableBytes() < 4){
            return;
        }
        //标记读索引
        in.markReaderIndex();
        int dataLength = in.readInt();//读取预先存储的字节数目
        if (dataLength < 0) {
            channelHandlerContext.close();
        }
        //避免半包/粘包
        if (in.readableBytes() < dataLength) {
            //重置读索引
            in.resetReaderIndex();
            return;
        }
        byte[] data = new byte[dataLength];
        in.readBytes(data);
        Object obj = SerializerEngine.deserialize(data, clazz, serializerType.getDisplayName());
        out.add(obj);
    }
}
